package com.five.admin.controller;

import com.five.admin.server.AliyunOssService;
import com.five.admin.server.ImageService;
import com.five.core.result.Result;
import com.five.core.result.ResultEnum;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/image")
public class ImageController {
    private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList(".jpg", ".jpeg", ".png", ".bmp");
    @Resource
    private AliyunOssService aliyunOssService;
    @Resource
    private ImageService imageService;

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("image") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.buildFail(ResultEnum.FILE_TYPE_ERROR);
        }
        // 2. 获取文件名和后缀
        String originalFileName = file.getOriginalFilename();
        if (originalFileName == null || !originalFileName.contains(".")) {
            return Result.buildFail(ResultEnum.FILE_TYPE_ERROR);
        }
        // 提取后缀并转为小写（统一格式，避免大小写问题）
        String extName = originalFileName.substring(originalFileName.lastIndexOf(".")).toLowerCase();

        // 3. 校验文件格式
        if (!ALLOWED_EXTENSIONS.contains(extName)) {
            return Result.buildFail(ResultEnum.FILE_TYPE_ERROR);
        }
        try {
            // 创建临时文件
            Path tempFile = Files.createTempFile("upload-", extName);
            file.transferTo(tempFile);

            String fileurl = aliyunOssService.uploadFile(tempFile.toFile());

            // 删除临时文件
            Files.deleteIfExists(tempFile);

            return Result.buildSuccess(fileurl);
        } catch (IOException e) {
            return Result.buildFail(ResultEnum.UNKNOWN_EXCEPTION.getCode(), "文件上传失败：" + e.getMessage());
        }
    }
}